﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using VSSTQH.DataAccess;

namespace VSSTQH
{
    public partial class FrmUsers : Form
    {

        #region Ctors
        private FrmUsers()
        {
            InitializeComponent();

            Initialize();

        }
        #endregion

        #region Singleton Members
        private static volatile FrmUsers instance;
        private static object syncRoot = new Object();

        public static FrmUsers Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new FrmUsers();
                }

                return instance;
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            instance = null;
            base.OnClosed(e);
        }

        #endregion

        #region Field Members
        IUserDAO _dataAccess = new UserDAO();
        IList<UserModel> _userList;
        #endregion

        #region Method Members

        /// <summary>
        /// Initialize methods of the application
        /// </summary>
        void Initialize()
        {
            this.btnReset.Click += new EventHandler(delegate { ClickButtonReset(); });
            this.btnSearch.Click += new EventHandler(delegate { ClickButtonSearch(); });
            this.btnNew.Click += new EventHandler(delegate { ClickButtonNew(); });
            this.btnEdit.Click += new EventHandler(delegate { ClickButtonEdit(); });
            this.btnDelete.Click += new EventHandler(delegate { ClickButtonDelete(); });
            // this.btnExcel.Click += new EventHandler(delegate { base.OnExportExcel(this.gridEX1); });
            this.btnClose.Click += new EventHandler(delegate
            {
                instance = null;
                this.Close();
            });
            this.btnResetPassword.Click += new EventHandler(delegate { ClickButtonResetPassword(); });
            this.gridEX1.DoubleClick += new EventHandler(delegate { ClickButtonEdit(); });

            // Get all products
            this.ClickButtonReset();

            // Set permission
            bool IsAdmin = (Common.UserLogin.GroupID == 1);
            this.btnDelete.Visible = IsAdmin;
            this.btnEdit.Visible = IsAdmin;
        }

        #endregion

        #region Action Members

        /// <summary>
        /// Click button reset
        /// </summary>
        private void ClickButtonReset()
        {
            // Reset Empty Value
            this.edtUsername.Text = String.Empty;

            // Execute Search
            this.ClickButtonSearch();

            // Focus First Control
            this.edtUsername.Focus();
        }

        /// <summary>
        /// Click button search
        /// </summary>
        private void ClickButtonSearch()
        {
            _dataAccess.SearchObject = new UserModel();
            _dataAccess.SearchObject.Username = this.edtUsername.Text;

            _userList = _dataAccess.Search();

            if (_userList == null || _userList.Count == 0)
                this.gridEX1.BuiltInTexts[Janus.Windows.GridEX.GridEXBuiltInText.GroupByBoxInfo] = "Không tìm thấy thông tin."; // Bạn phải nhập ít nhất 1 tiêu chí tìm kiếm.";
            else
            {
                if (Common.UserLogin.Username != Common.defaultUsername)
                {
                    var admin = _userList.Where(e => e.Username == "admin").SingleOrDefault();
                    if (admin != null)
                        _userList.Remove(admin);
                }
                this.gridEX1.BuiltInTexts[Janus.Windows.GridEX.GridEXBuiltInText.GroupByBoxInfo] = "Chọn cột cần group.";
            }

            this.gridEX1.DataSource = _userList;
        }

        /// <summary>
        /// Click button new
        /// </summary>
        private void ClickButtonNew()
        {
            int count = _userList.Count;
            // Show the updating staff instance
            FrmUpdateUsers instance = new FrmUpdateUsers();
            instance.Collection = _userList;
            instance.ShowDialog();
            if (count < _userList.Count)
            {
                //// Refresh data
                this.gridEX1.Refetch();
            }
        }

        /// <summary>
        /// Click button edit
        /// </summary>
        private void ClickButtonEdit()
        {
            if (this.gridEX1.CurrentRow == null)
            {
                //Library.Tools.MsgBox.Show(Messages.EditMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Edit user information
            FrmUpdateUsers instance = new FrmUpdateUsers();
            instance.User = this.gridEX1.CurrentRow.DataRow as UserModel;
            DialogResult result = instance.ShowDialog();
            if (result == DialogResult.OK)
            {
                // Refresh data
                this.gridEX1.Refetch();
            }
        }

        /// <summary>
        /// Click button delete
        /// </summary>
        private void ClickButtonDelete()
        {
            if (this.gridEX1.CurrentRow == null)
            {
                //Library.Tools.MsgBox.Show(Messages.DeleteMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            UserModel user = this.gridEX1.CurrentRow.DataRow as UserModel;
            bool? result = Common.ShowQuestion("Bạn có chắc xóa người dùng này không?");
            if (result.HasValue && result.Value)
            {
                if (_dataAccess.Delete(user))
                {
                    try
                    {
                        this.gridEX1.CurrentRow.Delete();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
                else
                    Common.ShowAlert("Không thể xóa người dùng này!");
            }
        }

        /// <summary>
        /// Click button reset password
        /// </summary>
        private void ClickButtonResetPassword()
        {
            bool? result = Common.ShowQuestion("Bạn có chắc sẽ reset password của những người dùng này không?");
            if (result.HasValue && result.Value)
            {
                int success, failed;
                if (_dataAccess.ResetPassword(_userList.Where(e => e.IsChecked), out success, out failed))
                {
                    Common.ShowSuccessful("Reset password thành công.");
                }

                // Refresh data
                this.gridEX1.Refetch();
            }
        }

        #endregion

    }
}
